package com.kfgj.hkp.common.utils;

import com.kfgj.hkp.common.exception.BaseException;
import com.kfgj.hkp.common.logging.Logger;
import com.kfgj.hkp.common.logging.LoggerFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.nio.charset.Charset;

/**
 * @version 1.0
 * @description TODO
 * @auth liwensihan
 * @date 2018/10/15 15:04
 */
public class HttpRequestUtils {

    private static Logger logger = LoggerFactory.getLogger(HttpRequestUtils.class);

    private static JsonMapper mapper = JsonMapper.nonDefaultMapper();

    public static <T> T requestPost(Object args, String url, Class<T> respCls, String contentType) {

        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();

            HttpPost post = new HttpPost(url);

            String reqMsg = "";
            if (args instanceof String) {
                reqMsg = (String) args;
            } else {
                reqMsg = mapper.toJson(args);
            }

            StringEntity stringEntity = new StringEntity(reqMsg,
                    ContentType.APPLICATION_JSON);
            stringEntity.setContentType(contentType);

            post.setEntity(stringEntity);

            HttpResponse response = httpClient.execute(post);

            HttpEntity entity = response.getEntity();
            T resp = null;
            if (respCls.equals(String.class)) {
                resp = (T) EntityUtils.toString(entity, Charset.forName("utf-8"));
            } else {
                resp = mapper.fromJson(
                        EntityUtils.toString(entity, Charset.forName("utf-8")),
                        respCls);
            }
            return resp;

        } catch (Exception e) {
            logger.error(e);
            throw new BaseException("调用接口服务端出现异常", e);
        }
    }

    public static <T> T requestGet(String url, Class<T> respCls) {

        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpGet post = new HttpGet(url);
            HttpResponse response = httpClient.execute(post);
            HttpEntity entity = response.getEntity();
            String json = EntityUtils.toString(entity, Charset.forName("utf-8"));

            logger.info("远程调用响应信息\n url:::[" + url + "]\n 响应类容信息：" + json);

            T resp = mapper.fromJson(json, respCls);
            return resp;

        } catch (Exception e) {
            logger.error(e);
            throw new BaseException("调用接口服务端出现异常", e);
        }
    }
}
